/*
 * NCSTCPServerConnection.cpp
 *
 *  Created on: Apr 17, 2017
 *      Author: zhangjf
 */

#include <Poco/Util/Application.h>

using namespace Poco::Util;

#include "Helper.h"
#include "Packet.h"
#include "PacketReceiver.h"
#include "PacketParams.h"
#include "CustomNotification.h"
#include "NetworkSubsystem.h"
#include "NCSTCPServerConnection.h"

namespace network
{

NCSTCPServerConnection::NCSTCPServerConnection(NotificationQueue& nq, const StreamSocket& socket)
: TCPServerConnection(socket)
, _nq(nq)
{
	// TODO Auto-generated constructor stub

}

NCSTCPServerConnection::~NCSTCPServerConnection()
{
	// TODO Auto-generated destructor stub
}

void NCSTCPServerConnection::run()
{
	PacketReceiver receiver(socket());
	try
	{
		while (true)
		{
			poco_information(NetworkSubsystem::instance().logger(), "wait to receive packet...");
			Packet* packet = receiver.recv();

			if (packet != nullptr)
			{
				Packet::Ptr p(packet);
				poco_information(NetworkSubsystem::instance().logger(), std::string("received packet: ") + p->getDataString());
				poco_information(NetworkSubsystem::instance().logger(), std::string("packet type: ") + std::to_string(p->getHeader()->type));

				PacketParams params(p, socket());
				CustomNotification<PacketParams> *pNotif = new CustomNotification<PacketParams>(params);
				_nq.enqueueNotification(pNotif);
			}
		}
	}
	catch (Poco::Exception& exc)
	{
		poco_information(NetworkSubsystem::instance().logger(), "AppServConnection: " + exc.displayText());
	}
}

} /* namespace network */
